<template>
    <div>
        <!-- 过滤条件区域 -->
        <a-card class="filter-card">
            <a-row :gutter="16" align="middle">
                <a-col :span="6">
                    <a-cascader
                        v-model="selectedData"
                        :options="cascaderOptions"
                        :placeholder="filterLabels.portPlaceholder"
                        style="width: 100%;"
                    />
                </a-col>
                <a-col :span="8">
                    <a-range-picker
                        ref="dateRangePicker"
                        v-model="dateRange"
                        :allow-clear="true"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        :placeholder="[filterLabels.startDate, filterLabels.endDate]"
                        show-time
                        format="YYYY-MM-DD HH:mm:ss"
                        :time-picker-props="{
                            format: 'HH:mm:ss'
                        }"
                        style="width: 100%;"
                        :open="pickerOpen"
                        @openChange="onPickerOpenChange"
                        @change="handleDateRangeChange"
                    >
                        <template slot="renderExtraFooter">
                            <div class="date-shortcuts">
                                <a-space wrap>
                                    <a-button 
                                        v-for="(shortcut, name) in shortCuts" 
                                        :key="name"
                                        size="small"
                                        class="shortcut-btn"
                                        @click="handleShortcutClick(name)"
                                    >
                                        {{ name }}
                                    </a-button>
                                </a-space>
                            </div>
                        </template>
                    </a-range-picker>
                </a-col>
                <a-col :span="6">
                    <a-space>
                        <a-button type="primary" @click="handleQuery">
                            {{ filterLabels.queryBtn }}
                        </a-button>
                        <a-button @click="handleExport">
                            {{ filterLabels.exportBtn }}
                        </a-button>
                    </a-space>
                </a-col>
            </a-row>
        </a-card>

        <!-- 数据表格 -->
        <a-card title="数据管理" class="table-card">
            <a-table
                :columns="tableColumns"
                :data-source="tableData"
                :pagination="paginationConfig"
                :loading="loading"
                row-key="id"
                @change="handleTableChange"
            />
        </a-card>
        <!-- 导出进度对话框 -->
        <a-modal
            v-model="exportDialogVisible"
            title="导出进度"
            :closable="false"
            :mask-closable="false"
            :footer="null"
            width="400px"
        >
            <a-progress :percent="exportPercentage" status="active" />
            <div style="text-align: center; margin-top: 16px;">
                正在导出数据，请稍候...
            </div>
        </a-modal>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
    name: 'DataManagement',
    data() {
        return {
            // 日期快捷选择配置
            shortCuts: {
                '今天': () => {
                    const now = new Date()
                    const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)
                    const end = new Date() // 选中那一刻的时间
                    return [start, end]
                },
                '最近一周': () => {
                    const end = new Date()
                    const start = new Date()
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                    return [start, end]
                },
                '本月': () => {
                    const end = new Date()
                    const start = new Date(end.getFullYear(), end.getMonth(), 1, 0, 0, 0)
                    return [start, end]
                },
                '最近30天': () => {
                    const end = new Date()
                    const start = new Date()
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                    return [start, end]
                }
            },
            
            // 过滤条件标签
            filterLabels: {
                portPlaceholder: '请选择端口/设备/变量',
                startDate: '开始时间',
                endDate: '结束时间',
                queryBtn: '查询',
                exportBtn: '导出'
            },
            
            // 级联选择数据
            selectedData: [],
            cascaderOptions: [],
            
            // 表格列定义
            tableColumns: [
                {
                    title: '序号',
                    dataIndex: 'index',
                    key: 'index',
                    width: 80,
                    align: 'center',
                    customRender: (text, record, index) => index + 1 + (this.paginationConfig.current - 1) * this.paginationConfig.pageSize
                },
                {
                    title: '时间',
                    dataIndex: 'time',
                    key: 'time',
                    sorter: true,
                    sortDirections: ['ascend', 'descend'],
                    defaultSortOrder: 'ascend'
                },
                {
                    title: '端口名称',
                    dataIndex: 'portName',
                    key: 'portName'
                },
                {
                    title: '设备名称',
                    dataIndex: 'deviceName',
                    key: 'deviceName'
                },
                {
                    title: '变量名称',
                    dataIndex: 'variableName',
                    key: 'variableName'
                },
                {
                    title: '值',
                    dataIndex: 'value',
                    key: 'value'
                }
            ],
            
            // 分页配置
            paginationConfig: {
                current: 1,
                pageSize: 10,
                total: 0,
                showSizeChanger: true,
                showQuickJumper: true,
                pageSizeOptions: ['10', '20', '50', '100'],
                showTotal: total => `共 ${total} 条`
            },
            
            // 表单数据
            dateRange: null,
            pickerOpen: false,
            
            // 表格数据
            tableData: [],
            loading: false,
            
            // 排序和过滤参数
            sortField: 'time',
            sortOrder: 'ascend',

            // 导出相关
            exportDialogVisible: false,
            exportPercentage: 0
        }
    },
    computed: {
        ...mapGetters('groupTree', ['deviceConnection'])
    },

    mounted() {
        // 组件挂载后初始化级联数据
        this.buildCascaderOptions()
    },
    
    methods: {
        checkParams() {
            if (!this.deviceConnection.ipAddress || !this.deviceConnection.port) {
                this.$message.error('请先在 "设备操作Tab" 中配置IP地址和端口')
                return false
            }
            return true
        },

        getParams() {
            if (!this.checkParams()) {
                return null
            }
            return this.deviceConnection.ipAddress + ':' + this.deviceConnection.port
        },        
        // 打开状态同步
        onPickerOpenChange(open) {
            this.pickerOpen = open
        },
        
        // 处理日期范围变化
        handleDateRangeChange(dates, dateStrings) {
            this.dateRange = (dateStrings && dateStrings.length) ? dateStrings : null
        },
        
        // 处理快捷日期选择
        handleShortcutClick(shortcutName) {
            let start
            let end = new Date()
            const now = new Date()

            switch (shortcutName) {
                case '今天':
                    start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)
                    end = new Date()
                    break
                case '最近一周':
                    start = new Date()
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                    end = new Date()
                    break
                case '本月':
                    start = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0)
                    end = new Date()
                    break
                case '最近30天':
                    start = new Date()
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                    end = new Date()
                    break
                default:
                    return
            }

            const dateRange = [this.$dayjs(start).format('YYYY-MM-DD HH:mm:ss'), this.$dayjs(end).format('YYYY-MM-DD HH:mm:ss')]

            // 设置选择器的值，显示清空按钮
            this.dateRange = dateRange

            // 关闭选择面板，无需点 OK
            this.pickerOpen = false
        },
        
        // 获取第一级选项数据
        async fetchFirstLevelOptions() {
            try {
                const host = this.getParams()
                const response = await this.fetchWithTimeout('http://' + host + '/v1/GetPortName', {
                    method: 'GET'
                })
                const data = await response.json()
                if (data.code === 0) {
                    // 将 portName 数组转换为 CascaderOption 格式
                    const portNames = data.msg?.portName || []
                    return portNames.map(name => ({
                        label: name,
                        value: name
                    }))
                } else {
                    this.$message.error('获取第一级选项失败: ' + (data.msg || '未知错误'))
                    return []
                }
            } catch (e) {
                this.$message.error('请求第一级选项超时或失败: ' + e.message)
                return []
            }
        },

        // 获取第二级选项数据
        async fetchSecondLevelOptions(parentValue) {
            try {
                const host = this.getParams()
                const response = await this.fetchWithTimeout(`http://${host}/v1/GetDevName?PortName=${parentValue}`, {
                    method: 'GET'
                })
                const data = await response.json()
                if (data.code === 0) {
                    const devNames = data.msg?.devName || data.msg || []
                    if (Array.isArray(devNames)) {
                        return devNames.map(name => ({
                            label: name,
                            value: name,
                            children: [] // 初始化空的children数组
                        }))
                    } else {
                        return []
                    }
                } else {
                    this.$message.error('获取第二级选项失败: ' + (data.msg || '未知错误'))
                    return []
                }
            } catch (e) {
                this.$message.error('请求第二级选项超时或失败: ' + e.message)
                return []
            }
        },

        // 获取第三级选项数据
        async fetchThirdLevelOptions(portName, devName) {
            try {
                const host = this.getParams()
                const response = await this.fetchWithTimeout(`http://${host}/v1/GetVarName?PortName=${portName}&DevName=${devName}`, {
                    method: 'GET'
                })
                const data = await response.json()
                if (data.code === 0) {
                    const varInfo = data.msg?.varInfo || []
                    if (Array.isArray(varInfo)) {
                        return varInfo.map(item => ({
                            label: item.varName,
                            value: item.variableId.toString()
                        }))
                    } else {
                        return []
                    }
                } else {
                    this.$message.error('获取第三级选项失败: ' + (data.msg || '未知错误'))
                    return []
                }
            } catch (e) {
                this.$message.error('请求第三级选项超时或失败: ' + e.message)
                return []
            }
        },

        // 构建完整的级联选项数据
        async buildCascaderOptions() {
            try {
                this.loading = true
                // 获取第一级选项
                const firstLevel = await this.fetchFirstLevelOptions()

                // 为每个第一级选项获取第二级选项
                for (const firstItem of firstLevel) {
                    const secondLevel = await this.fetchSecondLevelOptions(firstItem.value)

                    // 为每个第二级选项获取第三级选项
                    for (const secondItem of secondLevel) {
                        const thirdLevel = await this.fetchThirdLevelOptions(firstItem.value, secondItem.value)
                        this.$set(secondItem, 'children', thirdLevel)
                    }

                    this.$set(firstItem, 'children', secondLevel)
                }

                this.cascaderOptions = firstLevel
            } catch (error) {
                this.$message.error('构建级联选项失败')
            } finally {
                this.loading = false
            }
        },

        // 带超时的fetch请求
        fetchWithTimeout(resource, options = {}) {
            const TIMEOUT_MS = 12000
            return Promise.race([
                fetch(resource, options),
                new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), TIMEOUT_MS))
            ])
        },

        // 处理查询
        async handleQuery() {
            if (!this.checkParams()) {
                return
            }
            // 检查变量选择
            if (!this.selectedData || this.selectedData.length === 0) {
                this.$message.warning('请选择要查询的数据')
                return
            }

            // 检查时间范围
            if (!this.dateRange || this.dateRange.length !== 2) {
                this.$message.warning('请选择查询时间范围')
                return
            }

            const [portName, devName, variableId] = this.selectedData
            console.log(portName, devName, variableId)
            // 构建查询参数
            const requestBody = {
                variableId,
                startTime: new Date(this.dateRange[0]).getTime(),
                endTime: new Date(this.dateRange[1]).getTime(),
                currentPage: this.paginationConfig.current,
                pageSize: this.paginationConfig.pageSize
            }

            this.loading = true
            try {
                // 使用新的API endpoint
                const host = this.getParams()
                const response = await this.$axios.post(`http://${host}/v1/localHistoryRecord/queryLocalHistory`, requestBody)
                
                if (response?.data?.code === 0) {
                    // 处理新API的返回格式
                    this.tableData = response.data.msg.data || []
                    this.paginationConfig.total = response.data.msg.total || 0
                    this.$message.success('查询成功')
                } else {
                    this.$message.error('查询失败: ' + (response?.data?.msg || '未知错误'))
                }
            } catch (error) {
                console.error('Failed to fetch history data:', error)
                this.$message.error('查询请求失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading = false
            }
        },
        
        // 导出数据
        async handleExport() {
            if (!this.checkParams()) {
                return
            }
            if (!this.selectedData || this.selectedData.length === 0) {
                this.$message.warning('请先选择变量')
                return
            }
            if (!this.dateRange || !Array.isArray(this.dateRange) || this.dateRange.length !== 2) {
                this.$message.warning('请选择起始时间和结束时间')
                return
            }

            this.exportDialogVisible = true
            this.exportPercentage = 0

            const csvHeader = '时间,端口名,设备名,变量名,变量值\n'
            let mockCsvData = csvHeader

            const maxRecord = 1000
            let recordCount = 1000
            let totalCount = 0
            let sumCount = 0

            // 获取变量ID（最后一级）
            const [portName, devName, variableId] = this.selectedData
            console.log(portName, devName, variableId)
            const requestBody = {
                variableId,
                startTime: new Date(this.dateRange[0]).getTime(),
                endTime: new Date(this.dateRange[1]).getTime(),
                currentPage: 1,
                pageSize: maxRecord
            }

            try {
                // 获取总记录数
                const host = this.getParams()
                const totalResponse = await this.fetchWithTimeout('http://' + host + '/v1/localHistoryRecord/getTotal', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(requestBody)
                })
                const totalData = await totalResponse.json()
                totalCount = totalData.msg.total

                // 分批获取数据
                do {
                    const response = await this.fetchWithTimeout('http://' + host + '/v1/localHistoryRecord/exportHistory', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify(requestBody)
                    })
                    const data = await response.json()
                    
                    if (data.code !== 0) {
                        throw new Error(data.msg || '导出失败')
                    }
                    
                    recordCount = data.msg.data.length
                    sumCount += recordCount
                    this.exportPercentage = Math.floor((sumCount / totalCount) * 100)
                    mockCsvData += this.convertToCSV(data.msg.data)
                    requestBody.currentPage++
                } while (recordCount === maxRecord && sumCount < totalCount)

                // 创建并下载文件
                const timestamp = new Date().toISOString().split('T')[0]
                const suggestedFileName = `历史数据_${timestamp}.csv`
                const csvContent = '\ufeff' + mockCsvData
                
                try {
                    // 检查浏览器是否支持 File System Access API
                    if ('showSaveFilePicker' in window) {
                        console.log('✅ [DataManagement] 使用 File System Access API')
                        // 使用现代 API 让用户选择保存位置
                        const fileHandle = await window.showSaveFilePicker({
                            suggestedName: suggestedFileName,
                            types: [{
                                description: 'CSV 文件',
                                accept: { 'text/csv': ['.csv'] }
                            }]
                        })
                        
                        // 创建可写流并写入内容
                        const writable = await fileHandle.createWritable()
                        await writable.write(csvContent)
                        await writable.close()
                        
                        console.log('✅ [DataManagement] CSV文件保存成功')
                    } else {
                        console.log('⚠️ [DataManagement] 浏览器不支持 File System Access API，使用传统下载方式')
                        // 降级方案：使用传统的下载方式
                        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
                        const url = window.URL.createObjectURL(blob)
                        const link = document.createElement('a')
                        link.href = url
                        link.download = suggestedFileName
                        link.style.display = 'none'
                        
                        document.body.appendChild(link)
                        link.click()
                        
                        setTimeout(() => {
                            document.body.removeChild(link)
                            window.URL.revokeObjectURL(url)
                        }, 100)
                        
                        console.log('✅ [DataManagement] CSV文件下载触发成功（传统方式）')
                    }
                    
                    this.$message.success('导出成功')
                } catch (downloadError) {
                    // 用户取消保存或其他错误
                    if (downloadError.name === 'AbortError') {
                        console.log('ℹ️ [DataManagement] 用户取消了保存操作')
                        this.$message.info('已取消保存')
                    } else {
                        throw downloadError
                    }
                }
            } catch (error) {
                console.error('导出失败:', error)
                this.$message.error('导出失败: ' + error.message)
            } finally {
                this.exportDialogVisible = false
                this.exportPercentage = 0
            }
        },

        // 转换数据为CSV格式
        convertToCSV(objArray) {
            let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray
            let str = ''

            for (let i = 0; i < array.length; i++) {
                let line = ''
                line += array[i]['create_at']
                line += ','
                line += array[i]['port_name']
                line += ','
                line += array[i]['dev_name']
                line += ','
                line += array[i]['var_name']
                line += ','
                line += array[i]['value']
                str += line + '\r\n'
            }
            return str
        },
        
        // 表格变化处理（排序、过滤等）
        handleTableChange(pagination, filters, sorter) {
            this.paginationConfig.current = pagination.current
            this.paginationConfig.pageSize = pagination.pageSize
            
            if (sorter) {
                this.sortField = sorter.field
                this.sortOrder = sorter.order
            }
            
            this.handleQuery()
        },
        
        // 获取模拟数据
        getMockData() {
            const mockData = []
            const currentPage = this.paginationConfig.current
            const pageSize = this.paginationConfig.pageSize
            const start = (currentPage - 1) * pageSize
            
            for (let i = 0; i < pageSize; i++) {
                mockData.push({
                    id: start + i + 1,
                    time: new Date(Date.now() - Math.random() * 86400000 * 30).toLocaleString(),
                    portName: `端口${Math.floor(Math.random() * 5) + 1}`,
                    deviceName: `设备${Math.floor(Math.random() * 10) + 1}`,
                    variableName: `变量${Math.floor(Math.random() * 20) + 1}`,
                    value: (Math.random() * 100).toFixed(2)
                })
            }
            
            return mockData
        }
    }
}
</script>

<style scoped>
.filter-card {
    margin-bottom: 16px;
}
.filter-card :deep(.ant-card-body) {
    padding: 16px 24px;
}
.table-card :deep(.ant-card-body) {
    padding: 0;
}
.table-card :deep(.ant-table-wrapper) {
    padding: 0 24px 24px;
}
.table-card :deep(.ant-card-head) {
    border-bottom: 1px solid #f0f0f0;
}

/* 日期快捷选择样式 */
.date-shortcuts {
    padding: 8px 12px;
    border-top: 1px solid #f0f0f0;
    background-color: #fafafa;
}
.shortcut-btn {
    min-width: 60px;
    height: 24px;
    font-size: 12px;
    border-radius: 4px;
}
.shortcut-btn:hover {
    color: #1890ff;
    border-color: #1890ff;
}
</style> 